//
//  JoFileUpload.swift
//  JoTravel
//
//  Created by otisaldridge on 15/9/25.
//  Copyright © 2015年 zhuxietong. All rights reserved.

import Foundation
import UIKit
import JoLoading
import Alamofire
import Eelay

extension LoadResultType{
     public var errorImage:UIImage?{
        let img = UIImage(_snamed: "failed_error_tip")
        return img
    }
}


open class JoTaskLoading:JoLoading{
    
    public enum Mode {
        case loading
        case hide
        case alert
        public var isShow:Bool{
            switch self {
            case .hide:
                return false
            default:
                return true
            }
        }
    }
    
    public var mode:Mode = .hide{
        didSet{
            showing = mode.isShow
        }
    }
    
    public var loadingResult:LoadResultType? = nil
    open override func updateImage() {
        content.image = image
    }
    
    let bt = UIButton()
    
    required public init() {
        super.init(frame: .zero)
        self.addLayoutRules()
        resultClick = _ClickResult({[weak self] (r) in
            guard let ctr = self?.getSelfContainerController() else{
                return
            }
            switch r {
            case ._404,._500(code: _),._error(tip: _, tag: _),._offLine,._timeOut:
                if let page = ctr as? LinkOnlineRefreshProtocol{
                    page.refreshLinkView()
                    return
                }
                if let controller = ctr as? TypeInitController{
                    controller.mo_request_send()
                }
            default:
                break
            }
        })
        
        
    }
    
    
    
    
    
    required public init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func alertResult(result:LoadResultType?,handle:_ClickResult?=nil){
        self.result = result
        if let hand = handle{
            resultClick = hand
        }
        guard let result_ = result else{return}
        image = result?.errorImage
        switch result_ {
        case ._404,._500,._invalidAuth,._timeOut,._error,._offLine,._needAuth:
            show(message: result_.message, title: "")
            break
        case ._success(tip: _):
            dismiss()
        }
    }
    
    
    
    
    open func addLayoutRules() {
        eelay = [
            [content.view,[ee.T.L.B.R]],
            [bt,[ee.T.L.B.R]],
        ]
        content.backgroundColor = ._background
        bt.addTarget(self, action: #selector(clickAction), for: .touchUpInside)
//        bt.addTarget(self, action: #selector(clickAction), forControlEvents: .touchUpInside)
    }
    
    
    @objc func clickAction(){
        if self.alpha < 0.9{
            return
        }
        tapDialog()
    }
    
    
    @objc func tapDialog(){
        guard let r = result,let click = resultClick else {
            return
        }
        
        click.block(r)
    }
    
    public var content:JoTaskDialog = JoTaskDialog()
    
 
    open override func loading(message: String, title: String) {
        mode = .loading
        content.loading(message: message, title: title)
        self.addAnimation()
    }
    
    open override func handle(message: String, title: String, button: String, handAction: @escaping () -> Void) {
        content.handle(message: message, title: title, button: button, handAction: handAction)
        self.addAnimation()
    }
    
    
    
    
    open override func dismiss(animated: Bool = true) {
        mode = .hide
        content.dismiss(animated: animated)
        if animated
        {
            UIView.animate(withDuration: 0.34, animations: {[weak self]() -> Void in
                guard let `self` = self else{return}
                self.alpha = 0.0
            }) {[weak self](finish:Bool) -> Void in
                guard let `self` = self else{return}
                if self.mode == .hide{
                    self.alpha = 0.0
                }
                
            }
        }
        else
        {
            self.alpha = 0.0
        }
    }
    
    open override func show(message: String, title: String) {
        mode = .alert
        content.show(message: message, title: title)
        addAnimation()
    }
    
    
    
    
}
open class JoTaskDialog:MoDisplayNode{
    public let indicatorNode = ASDisplayNode { () -> UIView in
        if #available(iOS 13.0, *) {
            return UIActivityIndicatorView(style: .medium)
        } else {
            return UIActivityIndicatorView(style: .gray)
            // Fallback on earlier versions
        }
    }
    public var indicator:UIActivityIndicatorView?{
        return indicatorNode.view as? UIActivityIndicatorView
    }
    public let titleL = ASTextNode2()
    public let imgN = ASImageNode()
    public let messageL = ASTextNode2()
    
    public var image:UIImage? = nil{
        didSet{
            imgN.image = image
        }
    }
    public var title:String = ""{
        didSet{
            
            self.titleL.attributedText = "\(title)".ui.font15.center.color(color: ._foreground).astring
        }
    }
    public var message:String = ""{
        didSet{
            self.messageL.attributedText = "\(message)".ui.font14.center.color(color: ._weak).astring
        }
    }
    
    open override func addLayoutRules() {
        super.addLayoutRules()
    }
    
    
    public let button = ASButtonNode()
    public let buttonID = ""
    public var buttonName:String = ""{
        didSet{
            button.ui.font(font: .systemFont(ofSize: 13, weight: .ultraLight)).ntitle(title: buttonName).ncolor(color: ._weak)
        }
    }
    public var showing = false
    open var handBlock:()->Void = {
        
        print("press with block")
    }
    

    public enum Mode{
        case loading
        case error
        case handel
        case dismiss
    }
    
    public var mode = Mode.loading
    open func loading(message:String,title:String)
    {
        mode = .loading
        self.button.alpha = 0.0
        self.button.isEnabled = false
        
        self.title = title
        self.message = message

        self.indicator?.startAnimating()
        setNeedsLayout()
        layoutIfNeeded()
    }
    
    open func show(message:String,title:String)
    {
        mode = .error
        self.button.alpha = 0.0
        self.button.isEnabled = false
        
        self.title = title
        self.message = message
        self.indicator?.stopAnimating()
        setNeedsLayout()
        layoutIfNeeded()
    }
    
    open func handle(message:String,title:String,button:String,handAction:@escaping ()->Void)
    {
        mode = .handel
        
        self.handBlock = handAction
        self.button.alpha = 1.0
        self.button.isEnabled = true
        self.message = message
        self.title = title
        self.indicator?.stopAnimating()
        setNeedsLayout()
        layoutIfNeeded()
        
    }
    
    open func dismiss(animated:Bool=true)
    {
        mode = .dismiss
        self.title = ""
        self.message = ""
        self.indicator?.stopAnimating()
        self.button.alpha = 0.0
        self.button.isEnabled = false
        setNeedsLayout()
        layoutIfNeeded()
    }
    public override func specGetter() -> _Spec {
        let spec = _Spec.inset([], [20.fs], child: .stack(["v|\(10.fs)",&-.center,_justfy(.center)], childs: [
            .if(mode == .loading, spec: indicatorNode["20",20]),
            .if(mode != .loading && image != nil, spec: imgN["\(130.co)",130.co]),
            .if(title.len > 1 && mode != .loading, spec: titleL.Spec),
            .if(message.len > 1 && mode != .loading, spec: messageL.Spec),
            .if(mode != .loading && image != nil, spec: .stack(["80"], childs: [])),
        ]))
        return .inset([], .zero, child: spec)
    }
    
}


